﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.Entity.TD;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_PurchaseBusiness : BaseBusiness<PB_Purchase>, IPB_PurchaseBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        readonly IOperatorDept _opdept;
        public PB_PurchaseBusiness(IDbAccessor db, IOperator @operator, IOperatorDept @opdept)
            : base(db)
        {
            _operator = @operator;
            _opdept = @opdept;
        }

        #region 外部接口

        public async Task<PageResult<PB_Purchase>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_Purchase>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_Purchase, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 外采订单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_PurchaseDTO>> GetPurchaseDataListAsync(PageInput<PurchaseConditionDTO> input)
        {
            var where = LinqHelper.True<PB_PurchaseDTO>();
            var search = input.Search;
            Expression<Func<PB_Purchase, PB_Supplier, PB_PurchaseDTO>> select = (a, b) => new PB_PurchaseDTO
            {
                SuppName = b.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Purchase>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Supplier>() on a.SupplierId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PurchaseDTO, bool>(
                    ParsingConfig.Default, false, $@"Id.Contains(@0) or SuppName.Contains(@0) or Name.Contains(@0) or CreatorRealName.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            //获取登录人的部门信息
            var deptdata = await _opdept.GetOperatorDeptType();
            //登录人的部门类型是外协
            if (deptdata.DeptType == 8)
            {
                where = where.And(x => x.SupplierId == deptdata.SupplierId && x.Status >= 2);
            }
            else
            {
                where = where.And(x => _operator.Property.DeptIds.Contains(x.DeptId));
            }
            if (!search.Status.IsNullOrEmpty())
            {
                //status=99外采供应商建立货运派车
                if (search.Status == "99")
                {
                    where = where.And(x => (x.Status == 3 || x.Status == 4));
                }
                else
                {
                    where = where.And(x => x.Status == Convert.ToInt32(search.Status));
                }
            }
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 外采到货列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_PurchaseDTO>> GetPurchaseArrivalDataListAsync(PageInput<PurchaseConditionDTO> input)
        {
            var where = LinqHelper.True<PB_PurchaseDTO>();
            var search = input.Search;
            Expression<Func<PB_Purchase, PB_Supplier, PB_PurchaseDTO>> select = (a, b) => new PB_PurchaseDTO
            {
                SuppName = b.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_Purchase>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Supplier>() on a.SupplierId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_PurchaseDTO, bool>(
                    ParsingConfig.Default, false, $@"Id.Contains(@0) or SuppName.Contains(@0) or Name.Contains(@0) or CreatorRealName.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            if (!search.Status.IsNullOrEmpty())
            { 
                where = where.And(x => x.Status == Convert.ToInt32(search.Status));
            }
            else
            {
                where = where.And(x => (x.Status == 3 || x.Status == 4 || x.Status == 5));
            }
            where = where.And(x => _operator.Property.DeptIds.Contains(x.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        /// <summary>
        /// 查看外采订单信息
        /// </summary>
        /// <param name="PurchaseId">外采订单Id</param>
        /// <returns></returns>
        public async Task<PB_PurchaseDataDTO> GetPurchaseDataAsync(string PurchaseId)
        {
            Expression<Func<PB_PurchaseDetail, PB_Material, PurchaseDetailDTO>> select = (a, b) => new PurchaseDetailDTO
            {
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                ProductCode = b.ProductCode,
                IsNumber = b.IsNumber,
                IsProduct = b.IsProduct,
                PackageNum = b.PackageNum,
                IsSingle = b.IsSingle
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PurchaseDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            List<PurchaseDetailDTO> detaildata = await q.Where(x => x.ParentId == PurchaseId).ToListAsync();
            PB_Purchase pbdata = await Db.GetIQueryable<PB_Purchase>().Where(x => x.Id == PurchaseId).FirstOrDefaultAsync();

            Base_Department deptdata = new Base_Department();

            TD_Receiving recedata = await Db.GetIQueryable<TD_Receiving>().Where(x => x.OrderId == PurchaseId).FirstOrDefaultAsync();
            if (recedata != null) {
                deptdata = await Db.GetIQueryable<Base_Department>().Where(x => x.Id == recedata.StorId).FirstOrDefaultAsync();
            }

            PB_PurchaseDataDTO pp = new PB_PurchaseDataDTO();
            pp.Id = pbdata.Id;
            pp.Name = pbdata.Name;
            pp.DeptId = pbdata.DeptId;
            pp.PurchaseDate = pbdata.PurchaseDate;
            pp.HandoverDate = pbdata.HandoverDate;
            pp.SupplierId = pbdata.SupplierId;
            pp.Rate = pbdata.Rate;
            pp.TotalAmount = pbdata.TotalAmount;
            pp.TotalWeight = pbdata.TotalWeight;
            pp.Remarks = pbdata.Remarks;
            pp.Status = pbdata.Status;
            pp.CreatorId = pbdata.CreatorId;
            pp.CreatorRealName = pbdata.CreatorRealName;
            pp.CreateTime = pbdata.CreateTime;
            pp.Deleted = pbdata.Deleted;
            pp.QrCode = pbdata.QrCode;
            pp.PurchaseDetail = detaildata;
            pp.StorId = recedata == null ? "" : recedata.StorId;
            pp.StorName = deptdata == null ? "" : deptdata.Name;
            return pp;
        }

        /// <summary>
        /// 保存外采订单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task SavePurchaseDataAsync(PurchaseData data)
        {
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            if (data.Id.IsNullOrEmpty())
            {
                string pid = IdHelper.GetId();

                List<PB_PurchaseDetail> listdata = new List<PB_PurchaseDetail>();
                foreach (var item in data.PurchaseDetail)
                {
                    PB_PurchaseDetail pd = new PB_PurchaseDetail();
                    pd.Id = IdHelper.GetId();
                    pd.ParentId = pid;
                    pd.MaterialId = item.MaterialId;
                    pd.Nums = item.Nums;
                    pd.Price = item.Price;
                    pd.Amount = item.Amount;
                    pd.Weight = item.Weight;
                    pd.TotalWeight = item.TotalWeight;
                    pd.Remarks = item.Remarks;
                    pd.CreatorId = _operator.UserId;
                    pd.CreatorRealName = userdata.RealName;
                    pd.CreateTime = DateTime.Now;
                    pd.Deleted = false;
                    listdata.Add(pd);
                }

                PB_Purchase pp = new PB_Purchase();
                pp.Id = pid;
                pp.Name = data.Name;
                pp.DeptId = userdata.DepartmentId;
                pp.PurchaseDate = data.PurchaseDate;
                pp.HandoverDate = data.HandoverDate;
                pp.SupplierId = data.SupplierId;
                pp.Rate = data.Rate;
                pp.TotalAmount = data.TotalAmount;
                pp.TotalWeight = data.TotalWeight;
                pp.Remarks = data.Remarks;
                pp.Status = 1;
                pp.CreatorId = _operator.UserId;
                pp.CreatorRealName = userdata.RealName;
                pp.CreateTime = DateTime.Now;
                pp.Deleted = false;
                pp.QrCode = h_Purchase + "," + pid;

                await Db.InsertAsync<PB_PurchaseDetail>(listdata);
                await Db.InsertAsync<PB_Purchase>(pp);
            }
            else
            {
                //删除明细信息
                string sqlMain = @" delete from PB_PurchaseDetail where ParentId='" + data.Id + "'; ";
                await ExecuteSqlAsync(sqlMain);

                List<PB_PurchaseDetail> listdata = new List<PB_PurchaseDetail>();
                foreach (var item in data.PurchaseDetail)
                {
                    PB_PurchaseDetail pd = new PB_PurchaseDetail();
                    pd.Id = IdHelper.GetId();
                    pd.ParentId = data.Id;
                    pd.MaterialId = item.MaterialId;
                    pd.Nums = item.Nums;
                    pd.Price = item.Price;
                    pd.Amount = item.Amount;
                    pd.Weight = item.Weight;
                    pd.TotalWeight = item.TotalWeight;
                    pd.Remarks = item.Remarks;
                    pd.CreatorId = _operator.UserId;
                    pd.CreatorRealName = userdata.RealName;
                    pd.CreateTime = DateTime.Now;
                    pd.Deleted = false;
                    listdata.Add(pd);
                }

                await Db.InsertAsync<PB_PurchaseDetail>(listdata);

                sqlMain = @" update PB_Purchase set Name='"+ data.Name +"',PurchaseDate='" + Convert.ToDateTime(data.PurchaseDate).ToString("yyyy-MM-dd") + "',HandoverDate='" + Convert.ToDateTime(data.HandoverDate).ToString("yyyy-MM-dd") + "',SupplierId='" + data.SupplierId + "',Rate='" + data.Rate + "',Remarks='" + data.Remarks + "',TotalAmount='" + data.TotalAmount + "',TotalWeight='" + data.TotalWeight + "' where Id='" + data.Id + "' ";
                await ExecuteSqlAsync(sqlMain);

            }

        }

        /// <summary>
        /// 审核外采订单
        /// </summary>
        /// <param name="PurchaseId">外采订单Id</param>
        /// <returns></returns>
        public async Task ToExaminePurchaseDataAsync(string PurchaseId)
        {
            string sqlMain = @" update PB_Purchase set `Status`=2 where Id='" + PurchaseId + "' ";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 获取外采订单明细信息
        /// </summary>
        /// <param name="PurchaseId">外采订单Id</param>
        /// <returns></returns>
        public async Task<List<PurchasePrintDTO>> GetPurchaseDetailListAsync(string PurchaseId)
        {
            string sqlMain = @"select a.Id,a.ParentId as PurchaseId,a.MaterialId,a.Nums as RecNum,b.`Code` as MaterialCode,b.`Name` as MaterialName,b.Spec as MaterialSpec,IFNULL(c.Nums,0) AS Nums,IFNULL(d.packnums,0) AS packnums,b.IsSingle from PB_PurchaseDetail as a join PB_Material as b on a.MaterialId=b.Id left join (select MaterialId,IFNULL(COUNT(MaterialId),0) as nums from PB_JobBookingQrCode where PurchaseId='" + PurchaseId + "' group by MaterialId) as c on a.MaterialId=c.MaterialId left join (select PackId,MaterialId,IFNULL(COUNT(PackId),0) as packnums from PB_JobBookingQrCode where PurchaseId='" + PurchaseId + "' group by PackId,MaterialId) as d on a.MaterialId=d.MaterialId  where a.ParentId='" + PurchaseId + "'";
            return await Db.GetListBySqlAsync<PurchasePrintDTO>(sqlMain);
        }

        /// <summary>
        /// 外采单确认
        /// </summary>
        /// <param name="PurchaseId"></param>
        /// <returns></returns>
        public async Task DeterminePurchaseDataAsync(string PurchaseId)
        {
            string sqlMain = @" update PB_Purchase set `Status`=3 where Id='" + PurchaseId + "' ";
            await ExecuteSqlAsync(sqlMain);
        }

        /// <summary>
        /// 外采订单打码
        /// </summary>
        /// <param name="data">外采订单Id</param>
        /// <param name="_mongodbOptions"></param>
        /// <param name="_redisOptions"></param>
        /// <returns></returns>
        [Transactional]
        public async Task PrintPurchaseAsync(PurchasePrintData data, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            //获取外采订单的明细信息
            Expression<Func<PB_PurchaseDetail, PB_Material, PurchaseDetailDTO>> select = (a, b) => new PurchaseDetailDTO
            {
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                ProductCode = b.ProductCode,
                IsNumber = b.IsNumber,
                IsProduct = b.IsProduct,
                PackageNum = b.PackageNum,
                IsSingle = b.IsSingle
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_PurchaseDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            List<PurchaseDetailDTO> detaildata = await q.Where(x => x.ParentId == data.PurchaseId && data.liststr.Contains(x.Id)).ToListAsync();
            //时间戳
            string timestamp = GetTimeStamp();
            //推送队列物料批次
            string strguid = Guid.NewGuid().ToString("N");
            //推送队列包批次
            string packguid = Guid.NewGuid().ToString("N");
            //实例化Redis操作类
            _redisOptions.DbChannel = (int)Redis_Type.redis6;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            List<PB_PackList> listpack = new List<PB_PackList>();
            List<PrintQueue> listdata = new List<PrintQueue>();
            List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
            List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            List<PB_Printer> printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => x.DeptId == bdata.FactoryId).ToListAsync();
            string packprinterId = "";
            string materialprinterId = "";
            if (printerdata.Count == 0)
            {
                throw new BusException("请先维护打印机信息");
            }
            else
            {
                if (printerdata.Where(x => x.Type == "PrintPackage").FirstOrDefault() != null)
                {
                    packprinterId = printerdata.Where(x => x.Type == "PrintPackage").FirstOrDefault().Id;
                }
                else
                {
                    throw new BusException("请维护包码打印机");
                }
                if (printerdata.Where(x => x.Type == "PrintMaterial").FirstOrDefault() != null)
                {
                    materialprinterId = printerdata.Where(x => x.Type == "PrintMaterial").FirstOrDefault().Id;
                }
                else
                {
                    throw new BusException("请维护物料打印机");
                }
            }
            var deptdata = await _opdept.GetOperatorDeptType();

            //统计推送队列物料数量
            double jobcount = 0;
            //统计推送队列的包数量
            double jobpackcount = 0;
            foreach (var item in detaildata)
            {
                if (item.IsSingle == true)
                {
                    jobcount += 1;
                }
                else
                {
                    //计算打包的数量
                    decimal packquantity = Math.Ceiling(Convert.ToDecimal(item.Nums) / Convert.ToDecimal(item.PackageNum));
                    if (item.IsNumber == true)
                    {
                        jobcount += Convert.ToDouble(packquantity);
                        jobcount += Convert.ToDouble(item.Nums);
                        jobpackcount += Convert.ToDouble(packquantity);
                    }
                    else
                    {
                        jobcount += Convert.ToDouble(packquantity * 2);
                        jobpackcount += Convert.ToDouble(packquantity);
                    }
                }
            }

            foreach (var item in detaildata)
            {
                if (item.IsSingle == true)
                {
                    PrintQueue pq = new PrintQueue();
                    PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();

                    string jobcodeId = IdHelper.GetId();   //成品档案表ID
                    pq.Id = IdHelper.GetId();
                    pq.Name = item.MaterialName;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = deptdata.DeptName;
                    if (RedisSetHelper.Exists("QualityTestingNumber"))
                    {
                        string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                        if (redis.GetString("QualityTestingTime") == thedate)
                        {
                            redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                        else
                        {
                            redis.SetString("QualityTestingTime", thedate);
                            redis.SetString("QualityTestingNumber", "1");
                            pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                        }
                    }
                    else
                    {
                        redis.SetString("QualityTestingNumber", "0");
                    }
                    pq.QrCode = h_Material + "," + item.MaterialId;
                    pq.TypeName = item.MaterialSpec;
                    pq.Type = Skill_Type.Statistics.ToString();
                    pq.Status = item.Nums.ToString();
                    pq.Printer = materialprinterId;
                    pq.IsProduct = item.IsProduct;
                    pq.BatchNumber = strguid;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.JobCount = jobcount;
                    listdata.Add(pq);
                    jkcode.Id = jobcodeId;
                    jkcode.QrCode = h_Material + "," + item.MaterialId;
                    jkcode.MaterialId = item.MaterialId;
                    jkcode.MaterialName = item.MaterialName;
                    jkcode.OldOrNew = 1;
                    jkcode.RecId = "";
                    jkcode.PurchaseId = data.PurchaseId;
                    listcode.Add(jkcode);
                    PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                    pbdata.Id = IdHelper.GetId();
                    pbdata.No = item.Id;
                    pbdata.Nums = 1;
                    pbdata.DeptId = deptdata.DetpId;
                    pbdata.OperationUserId = _operator.UserId;
                    pbdata.OperationUserName = bdata.RealName;
                    pbdata.OperationTime = DateTime.Now;
                    pbdata.Type = 5;
                    pbdata.OldOrNew = 1;
                    pbdata.PrinterId = materialprinterId;
                    pbdetailed.Add(pbdata);
                }
                else
                {
                    //计算打包的数量
                    decimal packquantity = Math.Ceiling(Convert.ToDecimal(item.Nums) / Convert.ToDecimal(item.PackageNum));
                    if (item.IsNumber == true)
                    {
                        double dcount = 0;  //已生成包的物料数量
                        double dindex = 0; //每个包的包装数量
                        for (int i = 0; i < packquantity; i++)
                        {
                            PrintQueue printdata = new PrintQueue();
                            PB_PackList packdata = new PB_PackList();
                            //包名称
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            //包id
                            string packId = IdHelper.GetId();

                            dcount = Convert.ToDouble(item.PackageNum) * (i + 1);
                            if (dcount <= item.Nums)
                            {
                                dindex = Convert.ToDouble(item.PackageNum);
                            }
                            else
                            {
                                dindex = Convert.ToDouble(item.Nums) - Convert.ToDouble(item.PackageNum) * i;
                            }
                            for (int j = 0; j < dindex; j++)
                            {
                                if (j == 0)
                                {
                                    packdata.BoxName = item.MaterialName;
                                    packdata.MaterialId = item.MaterialId;
                                    printdata.Name = item.MaterialName;
                                    printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                    printdata.IsProduct = item.IsProduct;
                                }
                                //生成成品Id
                                PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                                string jobcodeId = IdHelper.GetId();   //成品档案表ID
                                if (RedisSetHelper.Exists("QualityTestingNumber"))
                                {
                                    string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                    if (redis.GetString("QualityTestingTime") == thedate)
                                    {
                                        redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                    else
                                    {
                                        redis.SetString("QualityTestingTime", thedate);
                                        redis.SetString("QualityTestingNumber", "1");
                                        jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    }
                                }
                                else
                                {
                                    redis.SetString("QualityTestingNumber", "0");
                                }
                                jkcode.Id = jobcodeId;
                                jkcode.ParentId = "";
                                jkcode.OrderId = "";
                                jkcode.OrderDetailId = "";
                                jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                                jkcode.MaterialId = item.MaterialId;
                                jkcode.MaterialName = item.MaterialName;
                                jkcode.OldOrNew = 1;
                                jkcode.RecId = "";
                                jkcode.PurchaseId = data.PurchaseId;
                                listcode.Add(jkcode);

                                //成品码推送
                                PrintQueue materprint = new PrintQueue();
                                materprint.Id = IdHelper.GetId();
                                materprint.No = jobcodeId;
                                materprint.Name = item.MaterialName;
                                materprint.TypeName = item.MaterialSpec;
                                materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                                materprint.Dept = deptdata.DeptName;
                                materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                                materprint.Type = Skill_Type.Statistics.ToString();
                                materprint.Status = "0";
                                materprint.Printer = materialprinterId;
                                materprint.IsProduct = item.IsProduct;
                                materprint.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                                materprint.BatchNumber = strguid;
                                materprint.JobCount = jobcount;
                                listdata.Add(materprint);
                            }
                            //每次成品码推送前把包信息放到成品码前面
                            PrintQueue pq = new PrintQueue();
                            pq.Id = IdHelper.GetId();
                            pq.No = packId;
                            pq.Name = "分割线";
                            pq.TypeName = "--------------------------";
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = "";
                            pq.QrCode = h_Pack + "," + packId;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = materialprinterId;
                            pq.IsProduct = true;
                            pq.Code = "";
                            pq.BatchNumber = strguid;
                            pq.JobCount = jobcount;
                            listdata.Add(pq);

                            //包信息
                            packdata.Id = packId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.Status = 0;
                            packdata.Type = 1;
                            packdata.State = true;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorId = _operator.UserId;
                            packdata.Deleted = false;
                            packdata.CreatorName = bdata.RealName;
                            packdata.Nums = dindex;
                            packdata.QrCode = h_Pack + "," + packId;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.OldOrNew = 1;
                            packdata.PackageType = 0;
                            packdata.IsUnpacking = dindex == item.PackageNum ? false : true;
                            listpack.Add(packdata);

                            //推送包信息到打印队列
                            printdata.Id = IdHelper.GetId();
                            printdata.No = packId;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = deptdata.DeptName;
                            printdata.BatchNumber = timestamp;
                            printdata.QrCode = h_Pack + "," + packId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = packprinterId;
                            printdata.TypeName = item.MaterialSpec;
                            printdata.BatchNumber = packguid;
                            printdata.JobCount = jobpackcount;
                            listdata.Add(printdata);

                        }
                        //生成成品记录
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = item.Nums;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 5;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = materialprinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        double dcount = 0;  //已生成包的物料数量
                        double dindex = 0; //每个包的包装数量
                        for (int i = 0; i < packquantity; i++)
                        {
                            PrintQueue printdata = new PrintQueue();
                            PB_PackList packdata = new PB_PackList();
                            //包名称
                            string dataName = "bag_" + timestamp + "_" + (i + 1);
                            //包id
                            string packId = IdHelper.GetId();

                            dcount = Convert.ToDouble(item.PackageNum) * (i + 1);
                            if (dcount <= item.Nums)
                            {
                                dindex = Convert.ToDouble(item.PackageNum);
                            }
                            else
                            {
                                dindex = Convert.ToDouble(item.Nums) - Convert.ToDouble(item.PackageNum) * i;
                            }
                            //生成成品Id
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            jkcode.Id = jobcodeId;
                            jkcode.ParentId = "";
                            jkcode.OrderId = "";
                            jkcode.OrderDetailId = "";
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.OldOrNew = 1;
                            jkcode.RecId = "";
                            jkcode.PurchaseId = data.PurchaseId;
                            listcode.Add(jkcode);

                            //成品码推送
                            PrintQueue materprint = new PrintQueue();
                            materprint.Id = IdHelper.GetId();
                            materprint.No = jobcodeId;
                            materprint.Name = item.MaterialName;
                            materprint.TypeName = item.MaterialSpec;
                            materprint.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            materprint.Dept = deptdata.DeptName;
                            materprint.QrCode = h_FinishedProduct + "," + jobcodeId;
                            materprint.Type = Skill_Type.Statistics.ToString();
                            materprint.Status = "0";
                            materprint.Printer = materialprinterId;
                            materprint.IsProduct = item.IsProduct;
                            materprint.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            materprint.BatchNumber = strguid;
                            materprint.JobCount = jobcount;
                            listdata.Add(materprint);

                            //每次成品码推送前把包信息放到成品码前面
                            PrintQueue pq = new PrintQueue();
                            pq.Id = IdHelper.GetId();
                            pq.No = packId;
                            pq.Name = "分割线";
                            pq.TypeName = "--------------------------";
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = "";
                            pq.QrCode = h_Pack + "," + packId;
                            pq.Type = Skill_Type.Statistics.ToString();
                            pq.Status = "0";
                            pq.Printer = materialprinterId;
                            pq.IsProduct = true;
                            pq.Code = "";
                            pq.BatchNumber = strguid;
                            pq.JobCount = jobcount;
                            listdata.Add(pq);

                            //包信息
                            packdata.Id = packId;
                            packdata.DeptId = bdata.DepartmentId;
                            packdata.BoxNo = dataName;
                            packdata.BoxName = item.MaterialName;
                            packdata.MaterialId = item.MaterialId;
                            printdata.Name = item.MaterialName;
                            printdata.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                            printdata.IsProduct = item.IsProduct;
                            packdata.Status = 0;
                            packdata.Type = 1;
                            packdata.State = true;
                            packdata.CreateTime = DateTime.Now;
                            packdata.CreatorId = _operator.UserId;
                            packdata.Deleted = false;
                            packdata.CreatorName = bdata.RealName;
                            packdata.Nums = dindex;
                            packdata.QrCode = h_Pack + "," + packId;
                            packdata.WorkshopId = bdata.DepartmentId;
                            packdata.OldOrNew = 1;
                            packdata.PackageType = 0;
                            packdata.IsUnpacking = dindex == item.PackageNum ? false : true;
                            listpack.Add(packdata);

                            //推送包信息到打印队列
                            printdata.Id = IdHelper.GetId();
                            printdata.No = packId;
                            printdata.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            printdata.Dept = deptdata.DeptName;
                            printdata.BatchNumber = timestamp;
                            printdata.QrCode = h_Pack + "," + packId;
                            printdata.Type = Skill_Type.Package.ToString();
                            printdata.Status = dindex.ToString();
                            printdata.Printer = packprinterId;
                            printdata.TypeName = item.MaterialSpec;
                            printdata.BatchNumber = packguid;
                            printdata.JobCount = jobpackcount;
                            listdata.Add(printdata);

                        }

                        //生成成品记录
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = item.Nums;
                        pbdata.DeptId = deptdata.DetpId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.Type = 5;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = materialprinterId;
                        pbdetailed.Add(pbdata);
                    }
                }
            }
            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
            listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
            {
                Id = x.Key.Id,
                No = x.Key.No,
                Name = x.Key.Name,
                TypeName = x.Key.TypeName,
                Date = x.Key.Date,
                Dept = x.Key.Dept,
                QrCode = x.Key.QrCode,
                Type = x.Key.Type,
                Status = x.Key.Status,
                Printer = x.Key.Printer
            }).ToList();
            //插入mongo队列
            await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            //插入mongo报工操作明细
            await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);
            //插入包信息
            await Db.InsertAsync<PB_PackList>(listpack);
            //统计完插入报工明细表二维码信息
            await Db.InsertAsync(listcode);
        }

        /// <summary>
        /// 外采订单成品码明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_JobBookingQrCodeDTO>> GetPurchaseDetailJobBookingQrCodeAsync(PageInput<PurchaseConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_JobBookingQrCodeDTO>> select = (a, b) => new PB_JobBookingQrCodeDTO
            {
                MaterialCode = b.Code,
                DeptId = b.DeptId,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            q = q.Where(x => x.PurchaseId == search.PurchaseId && x.MaterialId == search.MaterialId);
            return await q.GetPageResultAsync(input);
        }

        /// <summary>
        /// 成品物料补打
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task PrintPurchaseJobBookingQrCodeAsync(PurchaseMaterialPrintDataDTO data, MongoDBOptions _mongodbOptions)
        {
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingQrCodeDTO>> select = (a, b, c, d) => new PB_JobBookingQrCodeDTO
            {
                MaterialCode = b.Code,
                MaterialTypeName = c.Name,
                DeptId = b.DeptId,
                DeptName = d.Name,
                IsProduct = b.IsProduct,
                ProductCode = b.ProductCode,
                MaterialSpec = b.Spec,
                IsMine = b.IsMine
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on b.DeptId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            List<PrintQueue> listdata = new List<PrintQueue>();
            //推送队列批次
            string timestamp = Guid.NewGuid().ToString("N");
            
            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            PB_Printer printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => _operator.Property.DeptIds.Contains(x.WorkshopId) && x.Type == "PrintMaterial").FirstOrDefaultAsync();

            if (data.nums.Count >= 100)
            {
                PB_JobBookingQrCode jobdata = await Db.GetIQueryable<PB_JobBookingQrCode>().Where(x => x.Id == data.nums[0].ToString()).FirstOrDefaultAsync();
                var qdata = await q.Where(x => x.PurchaseId == data.PurchaseId && x.MaterialId == jobdata.MaterialId).ToListAsync();
                if (qdata.Count > 0)
                {
                    foreach (var item in qdata)
                    {
                        PrintQueue pq = new PrintQueue();
                        pq.Id = IdHelper.GetId();
                        pq.No = item.Id + "," + item.SerialNumber;
                        pq.Name = item.MaterialName;
                        pq.TypeName = item.MaterialSpec;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = item.DeptName;
                        pq.QrCode = item.QrCode;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = "0";
                        pq.Printer = printerdata.Id;
                        pq.IsProduct = item.IsProduct;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.BatchNumber = timestamp;
                        pq.JobCount = qdata.Count;
                        listdata.Add(pq);
                    }
                    MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                    //插入mongo队列
                    await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                }
                else
                {
                    throw new BusException("请选择后打印");
                }
            }
            else
            {
                var qdata = await q.Where(x => x.PurchaseId == data.PurchaseId && data.nums.Contains(x.Id)).ToListAsync();
                if (qdata.Count > 0)
                {
                    foreach (var item in qdata)
                    {
                        PrintQueue pq = new PrintQueue();
                        pq.Id = IdHelper.GetId();
                        pq.No = item.Id + "," + item.SerialNumber;
                        pq.Name = item.MaterialName;
                        pq.TypeName = item.MaterialSpec;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = item.DeptName;
                        pq.QrCode = item.QrCode;
                        pq.Type = Skill_Type.Statistics.ToString();
                        pq.Status = "0";
                        pq.Printer = printerdata.Id;
                        pq.IsProduct = item.IsProduct;
                        pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                        pq.BatchNumber = timestamp;
                        pq.JobCount = qdata.Count;
                        listdata.Add(pq);
                    }
                    MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                    //插入mongo队列
                    await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                }
                else
                {
                    throw new BusException("请选择后打印");
                }
            }
        }

        /// <summary>
        /// 外采订单包明细
        /// </summary>
        /// <param name="PurchaseId">外采订单Id</param>
        /// <param name="MaterialId">物料Id</param>
        /// <returns></returns>
        public async Task<List<PurchasePackList>> GetPurchasePackListAsync(string PurchaseId, string MaterialId)
        {
            string sqlMain = @"select c.Id,c.BoxName,a.MaterialId,d.`Name` as MaterialName,e.`Name` as MaterialTypeName,c.QrCode,f.`Name` as DeptName,a.PurchaseId from PB_JobBookingQrCode as a join PB_PackListInfo as b on a.Id=b.JobBookingId join PB_PackList as c on b.PackId=c.Id join PB_Material as d on a.MaterialId=d.Id join  PB_MaterialType as e on d.MaterialTypeId=e.Id join Base_Department as f on c.DeptId=f.Id where a.PurchaseId='" + PurchaseId + "' and a.MaterialId='" + MaterialId + "' GROUP BY c.Id,c.BoxName,a.MaterialId,d.`Name`,e.`Name`,c.QrCode,f.`Name`,a.PurchaseId";
            var listdata = await Db.GetListBySqlAsync<PurchasePackList>(sqlMain);
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 外采订单包码补打
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions"></param>
        /// <returns></returns>
        public async Task PrintPurchasePackListAsync(PurchaseMaterialPrintDataDTO data, MongoDBOptions _mongodbOptions)
        {
            string strid = string.Empty;
            foreach (var item in data.nums)
            {
                strid += "'" + item + "',";
            }
            strid = strid.Substring(0, strid.Length - 1);

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            PB_Printer printerdata = await Db.GetIQueryable<PB_Printer>().Where(x => _operator.Property.DeptIds.Contains(x.WorkshopId) && x.Type == "PrintPackage").FirstOrDefaultAsync();
            string sqlMain = @"SELECT a.Id,a.BoxName,a.MaterialId,d.`Code` as MaterialCode,d.Spec,d.ProductCode,d.IsProduct,d.`Name` as MaterialName,e.`Name` as MaterialTypeName,a.QrCode,f.`Name` as DeptName,c.PurchaseId,a.Nums,d.IsMine from PB_PackList AS a left join PB_PackListInfo as b on a.Id=b.PackId left join PB_JobBookingQrCode as c on b.JobBookingId=c.Id left join PB_Material as d on a.MaterialId=d.Id left join PB_MaterialType as e on d.MaterialTypeId=e.Id left join Base_Department as f on a.DeptId=f.Id where c.PurchaseId='"+ data.PurchaseId + "'and a.Id in (" + strid + ")   GROUP BY a.Id,a.BoxName,a.MaterialId,d.`Code`,d.`Name`,d.Spec,d.ProductCode,d.IsProduct,e.`Name`,a.QrCode,f.`Name`,c.PurchaseId,a.Nums,d.IsMine";
            var qdata = await Db.GetListBySqlAsync<PurchasePackList>(sqlMain);
            //推送批次
            string timestamp = Guid.NewGuid().ToString("N");
            if (qdata.Count > 0)
            {
                List<PrintQueue> listdata = new List<PrintQueue>();
                foreach (var item in qdata)
                {
                    PrintQueue pq = new PrintQueue();
                    pq.Id = IdHelper.GetId();
                    pq.No = item.Id;
                    pq.Name = item.BoxName;
                    pq.TypeName = item.Spec;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = item.DeptName;
                    pq.QrCode = item.QrCode;
                    pq.Type = Skill_Type.Package.ToString();
                    pq.Status = qdata.Count().ToString();
                    pq.Printer = printerdata.Id;
                    pq.IsProduct = item.IsProduct == null ? true : item.IsProduct;
                    pq.Code = item.IsProduct == true ? item.ProductCode : item.MaterialCode;
                    pq.BatchNumber = timestamp;
                    pq.JobCount = qdata.Count;
                    listdata.Add(pq);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            }
            else
            {
                throw new BusException("请选择后打印");
            }
        }

        /// <summary>
        /// 外采订单签收明细
        /// </summary>
        /// <param name="PurchaseId"></param>
        /// <returns></returns>
        public async Task<PB_PurchaseDataDTO> GetSurplusPurchaseDetailAsync(string PurchaseId)
        {
            PB_PurchaseDataDTO pp = new PB_PurchaseDataDTO();
            PB_Purchase pbdata = await Db.GetIQueryable<PB_Purchase>().Where(x => x.Id == PurchaseId).FirstOrDefaultAsync();

            string sqlMain = @" select *,(Nums-SignedQuantity) as Quantity  from (select a.Id,a.MaterialId,b.`Code` as MaterialCode,b.`Name` as MaterialName,b.Spec as MaterialSpec,a.Nums,a.Price,a.Amount,a.Weight,a.TotalWeight,a.Remarks,SUM(IFNULL(d.RecNum,0)) as SignedQuantity from PB_PurchaseDetail as a join PB_Material as b on a.MaterialId=b.Id left join TD_Receiving as c on a.ParentId=c.OrderId left join TD_RecDetail as d on c.Id=d.RecId and a.MaterialId=d.MaterialId where a.ParentId='" + PurchaseId + "' group by a.Id,a.MaterialId,b.`Code`,b.`Name`,b.Spec,a.Nums,a.Price,a.Amount,a.Weight,a.TotalWeight,a.Remarks ) as t ";
            List<SurplusPurchaseDetailDTO> Surpluslist = await Db.GetListBySqlAsync<SurplusPurchaseDetailDTO>(sqlMain);

            pp.Id = pbdata.Id;
            pp.Name = pbdata.Name;
            pp.DeptId = pbdata.DeptId;
            pp.PurchaseDate = pbdata.PurchaseDate;
            pp.HandoverDate = pbdata.HandoverDate;
            pp.SupplierId = pbdata.SupplierId;
            pp.Rate = pbdata.Rate;
            pp.TotalAmount = pbdata.TotalAmount;
            pp.TotalWeight = pbdata.TotalWeight;
            pp.Remarks = pbdata.Remarks;
            pp.Status = pbdata.Status;
            pp.CreatorId = pbdata.CreatorId;
            pp.CreatorRealName = pbdata.CreatorRealName;
            pp.CreateTime = pbdata.CreateTime;
            pp.Deleted = pbdata.Deleted;
            pp.QrCode = pbdata.QrCode;
            pp.SurplusPurchaseDetail = Surpluslist;
            pp.StorId = "";
            pp.StorName = "";
            return pp;
        }

        /// <summary>
        /// 外采订单签收
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [Transactional]
        public async Task UpdatePurchaseDataAsync(PB_PurchaseDataDTO data)
        {
            //查询外采订单明细信息
            List<SurplusPurchaseDetailDTO> Surpluslist = data.SurplusPurchaseDetail;

            Base_User userdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            //收货单Id
            string receId = IdHelper.GetId();
            List<TD_RecDetail> detaillist = new List<TD_RecDetail>();
            double dnum = 0;
            int index = 0;   //index=1部分签收;index=2已签收
            foreach (var item in Surpluslist)
            {
                double itemnums = Convert.ToDouble(item.Quantity + item.SignedQuantity);
                if (item.Nums == itemnums)
                {
                    if (index != 1)
                    {
                        index = 2;
                    }
                }
                else
                {
                    index = 1;
                }
                if (item.Quantity > 0)
                {
                    TD_RecDetail trd = new TD_RecDetail();
                    trd.Id = IdHelper.GetId();
                    trd.RecId = receId;
                    trd.StorId = data.StorId;
                    trd.MaterialId = item.MaterialId;
                    trd.Price = Convert.ToDouble(item.Price);
                    trd.PlanNum = Convert.ToDouble(item.Quantity);
                    trd.RecNum = Convert.ToDouble(item.Quantity);
                    trd.InNum = 0;
                    trd.Amount = Convert.ToDouble(item.Quantity * item.Price);
                    trd.CreateTime = DateTime.Now;
                    trd.CreatorId = _operator.UserId;
                    trd.Deleted = false;
                    trd.TaskId = data.Id;
                    detaillist.Add(trd);
                    dnum += Convert.ToDouble(item.Quantity);
                }
            }
            PB_Purchase pbdata = await Db.GetIQueryable<PB_Purchase>().Where(x => x.Id == data.Id).FirstOrDefaultAsync();
            TD_Receiving recedata = new TD_Receiving();
            recedata.Id = receId;
            recedata.StorId = data.StorId;
            recedata.Code = GetTimeStamp();
            recedata.OrderTime = DateTime.Now;
            recedata.RecTime = DateTime.Now;
            recedata.Type = "Purchase";
            recedata.RefCode = "";
            recedata.Status = 0;
            recedata.SupId = pbdata.SupplierId;
            recedata.TotalNum = dnum;
            recedata.InNum = 0;
            recedata.TotalAmt = Convert.ToDouble(pbdata.TotalAmount);
            recedata.CreateTime = DateTime.Now;
            recedata.CreatorId = _operator.UserId;
            recedata.Deleted = false;
            recedata.QrCode = h_TdRe + "," + receId;
            recedata.DeptId = userdata.DepartmentId;
            recedata.UpdateTime = DateTime.Now;
            recedata.OrderId = data.Id;

            //sqlMain = @"update PB_JobBookingQrCode set RecId='" + receId + "' where PurchaseId='" + data.Id + "'";
            //await ExecuteSqlAsync(sqlMain);

            await Db.InsertAsync<TD_RecDetail>(detaillist);
            await Db.InsertAsync<TD_Receiving>(recedata);

            ////修改外采订单状态
            string sqlMain = string.Empty;
            if (index == 2)
            {
                sqlMain = @" update PB_Purchase set `Status`=5 where Id='" + data.Id + "' ";
            }
            else if (index == 1)
            {
                sqlMain = @" update PB_Purchase set `Status`=4 where Id='" + data.Id + "' ";
            }
            await ExecuteSqlAsync(sqlMain);
        }

        public async Task<PB_Purchase> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_Purchase data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_Purchase data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            List<PB_Purchase> listdata = await Db.GetIQueryable<PB_Purchase>().Where(x => ids.Contains(x.Id)).ToListAsync();
            List<string> liststr = new List<string>();
            foreach (var item in listdata)
            {
                if (item.Status != 1)
                {
                    liststr.Add(item.Id);
                }
            }
            if (liststr.Count > 0)
            {
                throw new BusException("已审核的订单不能删除");
            }
            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}

